#include "Transport.h"

namespace cm_nat
{
    Transport::Transport():m_remoteCandidate(NULL)
    {

    }

    Transport::~Transport()
    {
        CandidateList::iterator it = m_candidates.begin();
        CandidateList::iterator it2;
        while( it != m_candidates.end() ){
            it2 = it++;
            delete (*it2);
            m_candidates.erase( it2 );
        }

        if( m_remoteCandidate ){
            delete m_remoteCandidate;
        }
    }

    bool Transport::addCandidate( Candidate* p_cand )
    {
        if( p_cand ){
            m_candidates.push_back(p_cand);
        }
        return true;
    }

    bool Transport::addRemoteCandidate(RemoteCandidate* p_rcand)
    {
        if(!m_remoteCandidate){
            m_remoteCandidate = p_rcand;
            return true;
        }else{
            return false;
        }
    }
    
    Tag* Transport::tag() const
    {
        Tag* p_tag = new Tag("transport");
        p_tag->setXmlns(XMLNS_JINGLE_ICE_UDP);
        p_tag->addAttribute("pwd", m_pwd);
        p_tag->addAttribute("ufrag", m_ufrag);

        CandidateList::const_iterator it= m_candidates.begin();
        for(; it!=m_candidates.end(); ++it ){
            p_tag->addChild( (*it)->tag() );
        }

        if( m_remoteCandidate ){
            p_tag->addChild( m_remoteCandidate->tag() );
        }

        return p_tag;
    }

    bool Transport::parse(Tag* p_tag)
    {
        if( p_tag->name() != "transport" )
            return false;

        m_pwd = p_tag->findAttribute("pwd");
        m_ufrag = p_tag->findAttribute("ufrag");

        const TagList& candidates = p_tag->findChildren( "candidate" );
        TagList::const_iterator it = candidates.begin();
        for( ; it != candidates.end(); ++it ){
            Candidate* p_cand = new Candidate;
            p_cand->parse( (*it) );
            addCandidate(p_cand);
        }

        Tag* rc = p_tag->findChild("remote-candidate");
        if( rc ){
            m_remoteCandidate = new RemoteCandidate;
            m_remoteCandidate->parse(rc);
        }

        return true;
    }

}